const Router = require('koa-router');
const crypto = require('crypto');
const sanitize = require('sanitize-html');
const query = require('../lib/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');

const router = new Router();

router.prefix('/api/feedback');

module.exports = router;

/**
 * 添加反馈意见
 */
router.post('/add', async (ctx, next) => {
  let { content } = ctx.request.body;

  if (!content) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  if (!sanitize(content)) {
    ctx.body = await wrapper(new Error('输入不合法.'));
    return false;
  }

  content = escape(sanitize(content));
  const addRes = await query(`INSERT INTO feedback (content,create_time) VALUES ("${content}",SYSDATE())`);
  if (checkError(addRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper('反馈成功');
});
